<template>
  <div>
    <el-form
      ref="formRef"
      :model="formModel"
      label-position="top"
      class="person-form"
    >
      <el-form-item label="人员信息" prop="person">
        <div class="person-list-container">
          <div
            v-for="(personItem, index) in formModel.person"
            :key="index"
            class="person-item-card"
          >
            <el-row :gutter="20" align="middle">
              <el-col :span="1" class="item-index-col">
                <span class="item-index">{{ index + 1 }}</span>
              </el-col>

              <el-col :span="19">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item
                      :prop="'person.' + index + '.name'"
                      :rules="rules.name"
                    >
                      <el-input
                        v-model="personItem.name"
                        placeholder="请输入姓名"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item
                      :prop="'person.' + index + '.ip'"
                      :rules="rules.ip"
                    >
                      <el-input
                        v-model="personItem.ip"
                        placeholder="例如: 192.168.1.1"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item
                      :prop="'person.' + index + '.mac'"
                      :rules="rules.mac"
                    >
                      <el-input
                        v-model="personItem.mac"
                        placeholder="例如: 00:1A:2B:3C:4D:5E"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

              <el-col :span="4" class="action-buttons">
                <el-button
                  v-if="index > 0"
                  type="danger"
                  :icon="Delete"
                  circle
                  @click="removePersonItem(index)"
                />
                <el-button
                  v-if="index === formModel.person.length - 1"
                  type="primary"
                  :icon="Plus"
                  circle
                  @click="addPersonItem"
                />
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form-item>

      <el-form-item class="form-footer">
        <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
        <el-button @click="resetForm(formRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
// script 部分与之前完全相同，无需任何修改
import { reactive, ref } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { Plus, Delete } from "@element-plus/icons-vue";

interface PersonItem {
  name: string;
  ip: string;
  mac: string;
}

const formRef = ref<FormInstance>();

const formModel = reactive<{ person: PersonItem[] }>({
  person: [{ name: "", ip: "", mac: "" }],
});

const validateIp = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("IP 地址不能为空"));
  }
  const ipv4Regex =
    /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
  if (!ipv4Regex.test(value)) {
    callback(new Error("请输入有效的 IPv4 地址"));
  } else {
    callback();
  }
};

const validateMac = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("MAC 地址不能为空"));
  }
  const macRegex = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/;
  if (!macRegex.test(value)) {
    callback(new Error("请输入有效的 MAC 地址，例如: 00:1A:2B:3C:4D:5E"));
  } else {
    callback();
  }
};

const rules = reactive<FormRules>({
  name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  ip: [{ required: true, validator: validateIp, trigger: "blur" }],
  mac: [{ required: true, validator: validateMac, trigger: "blur" }],
});

const addPersonItem = () => {
  formModel.person.push({ name: "", ip: "", mac: "" });
};

const removePersonItem = (index: number) => {
  formModel.person.splice(index, 1);
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("校验成功，提交的数据:", formModel.person);
      ElMessage({ message: "提交成功!", type: "success" });
    } else {
      console.log("校验失败:", fields);
      ElMessage({ message: "表单校验失败，请检查输入项。", type: "error" });
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formModel.person = [{ name: "", ip: "", mac: "" }];
  formEl.resetFields();
};
</script>

<style scoped>
/* 总容器样式：使用淡灰色背景 */
.person-list-container {
  width: 100%;
  padding: 16px;
  border-radius: 6px;
  /* 使用 Element Plus 的内置颜色变量，更具适应性 */
  background-color: var(--el-fill-color-light);
}

/* 单个信息条目卡片样式 */
.person-item-card {
  width: 100%;
  padding: 8px 16px 0 8px; /* 上8 右16 下0 左8 */
  border-radius: 4px;
  background-color: var(--el-bg-color); /* 使用纯白背景 */
  box-sizing: border-box;
}

/* 为非最后一个卡片添加下边距，取代分割线 */
.person-item-card:not(:last-child) {
  margin-bottom: 16px;
}

/* 移除卡片内表单项的标签（因为外部已有）和下边距 */
.person-item-card .el-form-item {
  margin-bottom: 16px;
}
/* vue3深度选择器，移除内部label */
:deep(.person-item-card .el-form-item__label) {
  display: none;
}

/* 序号列的样式 */
.item-index-col {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 序号本身的样式 */
.item-index {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-secondary);
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
}

.form-footer {
  margin-top: 20px;
  text-align: right; /* 让提交按钮靠右，更符合习惯 */
}
</style>
